//
//  RCLocationHandler.m
//  CoreLocationTest
//
//  Created by Miles on 10-05-11.
//  Copyright 2010 Miles Thorogood
//  greenmeat.net. All rights reserved.
//

#import "RCLocationHandler.h"
#import "RCCommunicationController.h"

@implementation RCLocationHandler
@synthesize locationManager ;

@synthesize locationMeasurements ;
@synthesize locationData ;
@synthesize aLocation ;

- (id) initWithDelegate:(id)del {
	self = [super init] ;
	if (self) {
		self.locationMeasurements = [NSMutableArray array] ;
		locDelegate = del;
		self.aLocation = [[CLLocation alloc] init] ;
		[self startLocationSystem] ;
	}
	return self ;
}

- (void) dealloc {
	[locationManager release] ;
	[locationMeasurements release] ;
	[aLocation release] ;
	[locationData release] ;
	[super dealloc] ;
}

- (void) startLocationSystem {
	self.locationManager = [[CLLocationManager alloc] init] ;
	locationManager.delegate = self ;
	locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters ; //kCLLocationAccuracyBest
	locationManager.distanceFilter = 100.0 ;
	[locationManager startUpdatingLocation] ;
	[locationManager startUpdatingHeading] ;
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	
	if (newLocation.horizontalAccuracy < 0) return;
    // test the age of the location measurement to determine if the measurement is cached
    // in most cases you will not want to rely on cached measurements
    NSTimeInterval locationAge = [newLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 5.0) return;
	
	
	
	if(newLocation != oldLocation) {
		printf("latitude %+.6f, longitude %+.6f\n",
			   newLocation.coordinate.latitude,
			   newLocation.coordinate.longitude) ;
		
		aLocation = newLocation ;
		[(RCCommunicationController *)locDelegate locationReceivedNotification:self];
		
		//NSLog(@"Location: %@\n", [newLocation description]);

	}
	
}

- (void)stopUpdatingLocation:(NSString *)state {
    [locationManager stopUpdatingLocation];
    locationManager.delegate = nil;
	printf("got to stop updating");
}

- (void) fillLocationData:(CLLocation *)location {
	/*	NSString *lat = [[NSString alloc] init] ;
	 lat = location.coordinate.latitude ;
	 [self.locationData setObject:lat forKey:@"lat"] ;
	 [self.locationData setObject:location.coordinate.longitude forKey:@"lon"] ;
	 [self.locationData setObject:location.altitude forKey:@"alt"] ;
	 [self.locationData setObject:location.speed forKey:@"speed"] ;
	 [self.locationData setObject:location.course forKey:@"heading"] ;
	 */
}
@end
